<template>
	<view class="wrap">
		<view class="add-wrap yf-flex-left">
			<view class="add-item" @click="chooseVideo(true)" v-if="!isprod">
				<video :src="videoPath" ref="videoRef" :controls="false" :http-cache="true" :page-gesture="false"
					:show-fullscreen-btn="false" :show-loading="false" :show-center-play-btn="false"
					:enable-progress-gesture="false" object-fit="cover" class="srcImg" v-if="videoPath" id="myVideo"
					@fullscreenchange="onFullscreenChange" />
				<view class="add-info yf-flex-center yf-flex-vertical" :class="videoPath ? 'yf-flex-right' : ''">
					<template v-if="!videoPath">
						<image src="/static/commen/addvideoIcon.png" mode="" class="add-img"></image>
						<view class="add-text"> 上传视频 </view>
					</template>
					<template v-else>
						<image src="/static/commen/playVideo.png" mode="" class="add-img" @click="lookDetail">
						</image>
						<view class="editImg" style="margin-top: 54rpx" @click.stop="chooseVideo()">
							更换视频
						</view>
					</template>
				</view>
			</view>
			<view class="add-item" @click="chooseImage(true)">
				<image :src="imagePath" mode="aspectFill" class="srcImg" v-if="imagePath">
				</image>
				<view class="add-info yf-flex-center yf-flex-vertical" :class="imagePath ? 'yf-flex-right' : ''">
					<template v-if="!imagePath">
						<image src="/static/commen/addimgIcon.png" mode="" class="add-img"></image>
						<view class="add-text"> 上传封面 </view>
					</template>
					<view class="editImg" @click.stop="chooseImage()" v-else>
						更换封面
					</view>
				</view>
			</view>
		</view>
		<input type="text" class="addInput" placeholder="添加标题" v-model="videoForm.videoTitle" />
		<textarea type="text" class="addTextarea" placeholder="添加正文" v-model="videoForm.videoText" />
		<!-- 提交  -->
		<view class="btn-wrap yf-flex-center savepadding">
			<view class="btn yf-flex-center" @click="submit">发布作品</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import indexConfig from "@/config/index.config.js";
	export default {
		data() {
			return {
				videoForm: {
					videoTitle: "",
					videoText: "",
					videoCoverUrl: "",
					videoUrl: "",
				},
				videoPath: "",
				imagePath: "",
				uploading: {
					image: false,
					video: false,
				},
				videoContext: null,
			};
		},
		computed: {
			...mapState("isprod"),
		},
		onReady() {
			// 小程序中，onReady 比 mounted 更适合获取组件上下文
			// #ifdef MP-WEIXIN
			// 在微信小程序中，通常在 onReady 钩子后，组件已渲染完成
			// this.videoContext = uni.createVideoContext("myVideo", this);
			// console.log("Video Context created in onReady:", this.videoContext);
			// #endif
		},
		methods: {
			lookDetail() { 
				this.$Router.navigateTo("preview",{url:this.videoPath})
			}, 
			submit() {
				let that = this;
				if (!this.isprod) {
					if (!this.videoForm.videoTitle) {
						this.$api.msg("请输入标题");
						return;
					}
					if (!this.videoForm.videoCoverUrl) {
						this.$api.msg("请上传封面");
						return;
					}
					this.$api.msg("发布成功");
					this.$Router.switchTab("tabBar-user");
					return;
				}
				// 如果有图片/视频，必须已上传成功（ID存在）
				if (this.uploading.image || this.uploading.video) {
					this.$api.msg("文件上传中，请稍候");
					return;
				}
				if (!this.videoForm.videoTitle) {
					this.$api.msg("请输入标题");
					return;
				}
				if (!this.videoForm.videoUrl) {
					this.$api.msg("请上传视频");
					return;
				}
				that.$api.showLoading();
				that.$apis
					.addVideoContent(this.videoForm)
					.then((result) => {
						if (result.code == 200) {
							that.$Router.switchTab("tabBar-user");
						}
					})
					.catch((err) => {
						setTimeout(() => {
							that.$api.hideLoading();
						}, 1500);
					});
			},
			// 选择图片
			chooseImage(isAdd = false) {
				if (this.imagePath && isAdd) return;
				uni.chooseImage({
					count: 1, // 最多选9张
					sizeType: ["compressed"], // 可以指定是原图还是压缩图
					sourceType: ["album", "camera"], // 从相册或相机选择
					success: (res) => {
						this.imagePath = res.tempFilePaths[0];
						this.uploadImages(); //图片文件上传
						console.log(res, "imagePathres");
					},
					fail: (err) => {
						console.error("选择图片失败", err);
					},
				});
			},

			// 预览图片
			previewImage(current) {
				uni.previewImage({
					current,
					urls: [this.imagePath],
				});
			},

			// 选择视频
			chooseVideo(isAdd = false) {
				if (this.videoPath && isAdd) return;
				uni.chooseVideo({
					sourceType: ["album", "camera"],
					maxDuration: 60, // 最长60秒（部分平台支持）
					camera: "back",
					success: (res) => {
						this.videoPath = res.tempFilePath;
						this.$nextTick(() => {
							// #ifdef MP-WEIXIN
							try {
								this.videoContext = uni.createVideoContext("myVideo", this);
							} catch (e) {
								console.warn("createVideoContext failed", e);
							}
							// #endif
						});
						this.uploadVideo(); //视频文件上传
						console.log(res, "videoPathres");
					},
					fail: (err) => {
						console.error("选择视频失败", err);
					},
				});
			},

			// 上传所有图片
			async uploadImages() {
				if (!this.imagePath) return;
				this.uploading.image = true;
				try {
					const result = await this.uploadFile(this.imagePath, "image");
					console.log("图片上传成功", result);
					// uni.showToast({
					// 	title: '图片上传成功',
					// 	icon: 'success'
					// });
					// this.imageList = []; // 清空
					this.videoForm.videoCoverUrl = result.data.url;
				} catch (err) {
					console.error("图片上传失败", err);
					uni.showToast({
						title: "上传失败",
						icon: "error",
					});
				} finally {
					this.uploading.image = false;
				}
			},

			// 上传视频
			async uploadVideo() {
				if (!this.videoPath) return;
				this.uploading.video = true;
				try {
					const result = await this.uploadFile(this.videoPath, "video");
					console.log("视频上传成功", result);
					// uni.showToast({
					// 	title: '视频上传成功',
					// 	icon: 'success'
					// });
					// this.videoPath = ''; // 清空
					this.videoForm.videoUrl = result.data.url;
				} catch (err) {
					console.error("视频上传失败", err);
					uni.showToast({
						title: "上传失败",
						icon: "error",
					});
				} finally {
					this.uploading.video = false;
				}
			},

			// 通用上传方法
			uploadFile(filePath, fileType) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: indexConfig.baseUrl + "cos/upload", // 替换为你的后端接口
						filePath: filePath,
						name: "file", // 后端接收的字段名，如 $_FILES['file']
						formData: {
							type: fileType, // 可选：传递额外参数
						},
						success: (res) => {
							if (res.statusCode === 200) {
								console.log(res.data, "res.data");
								const data = JSON.parse(res.data);
								resolve(data);
							} else {
								reject(new Error("服务器返回错误"));
							}
						},
						fail: (err) => {
							reject(err);
						},
					});
				});
			},
		},
	};
</script>

<style lang="scss">
	.wrap {
		padding: 30rpx 30rpx 120rpx;
	}

	.add-wrap {
		.add-item {
			position: relative;
			width: 232rpx;
			height: 316rpx;
			background: #f5f5f5;
			border-radius: 16rpx;
			margin-right: 20rpx;

			.srcImg {
				width: 232rpx;
				height: 316rpx;
				border-radius: 16rpx;
			}

			.add-info {
				width: 232rpx;
				height: 316rpx;
				border-radius: 16rpx;
				position: absolute;
				left: 0;
				top: 0;
				padding: 20rpx 0;

				.add-img {
					width: 60rpx;
					height: 60rpx;
				}

				.add-text {
					font-size: 24rpx;
					color: #74777f;
					margin-top: 20rpx;
				}

				.editImg {
					width: 128rpx;
					height: 54rpx;
					background: rgba(0, 0, 0, 0.4);
					border-radius: 28rpx;
					border: 1rpx solid rgba(255, 255, 255, 0.5);
					font-size: 22rpx;
					color: #ffffff;
					text-align: center;
					line-height: 52rpx;
				}
			}
		}
	}

	.addInput {
		font-size: 32rpx;
		color: #1e2124;
		width: 100%;
		margin: 40rpx 0 30rpx;
		height: 44rpx;
	}

	.addTextarea {
		font-size: 28rpx;
		color: #1e2124;
		width: 100%;
	}

	.btn-wrap {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background: #ffffff;
		min-height: 108rpx;
		z-index: 10;

		.btn {
			margin: 0 4%;
			height: 96rpx;
			background: linear-gradient(90deg, #92e082 0%, #22ccb1 100%);
			border-radius: 46rpx;
			color: #1e2124;
			font-size: 30rpx;
			width: 92%;
		}
	}
</style>